package com.vxdata.utils.modules.hbase.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lijj
 * @date 2020-03-29
 * 0.创建配置对象，获取habse的连接
 * 1.获取Habase连接对象
 * 2. 获取操作对象
 * 3.获取操作结果
 * 4.关闭数据库连接
 * 该类是封装数据库的连接和连接指定表的对象
 */
@Slf4j
@Component
@Order(value = 2)
public class HBaseConn {

    private static final HBaseConn INSTANCE = new HBaseConn();
    private static Configuration configuration;
    private static Connection connection;

    private HBaseConn() {
        try {
            if (configuration == null) {
                configuration = HBaseConfiguration.create();//创建配置对象，获取hbase的连接
                configuration.set("hbase.zookeeper.quorum", "192.168.20.54");
                configuration.set("hbase.zookeeper.property.clientPort", "2181");
                log.debug("=======================================");
                log.debug(GetPropertiesUtil.getQuorum());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库的连接
    private Connection getConnection() {
        if (connection == null || connection.isClosed()) {
            try {
                connection = ConnectionFactory.createConnection(configuration);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static Connection getHBaseConn() {
        return INSTANCE.getConnection();
    }

    public static Table getTable(String tableName) throws IOException {
        return INSTANCE.getConnection().getTable(TableName.valueOf(tableName));
    }

    public static void closeConn() {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
//        Configuration conf = HBaseConfiguration.create();
//        conf.set("hbase.zookeeper.quorum", "192.168.20.54");
//        conf.set("hbase.zookeeper.property.clientPort", "2181");
//        ConnectionFactory.createConnection(conf);
        Connection conn = HBaseConn.getHBaseConn();

    }

}